package com.vision.sales.salesinvoice.cl.ui;

import static com.vision.sales.cl.SalesServices.companySvc;
import static com.vision.sales.cl.SalesServices.customerSvc;
import static com.vision.sales.cl.SalesServices.productSvc;
import static com.vision.sales.cl.SalesServices.salesInvoiceSvc;
import static com.vision.sales.cl.SalesServices.salesmanSvc;

import java.util.ArrayList;
import java.util.List;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.data.client.loader.RpcProxy;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.Store;
import com.sencha.gxt.data.shared.loader.LoadEvent;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoader;
import com.sencha.gxt.widget.core.client.TabItemConfig;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.DateField;
import com.sencha.gxt.widget.core.client.form.NumberField;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor.DoublePropertyEditor;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.form.StoreFilterField;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.form.validator.MaxLengthValidator;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.menu.CheckMenuItem;
import com.sencha.gxt.widget.core.client.menu.Item;
import com.sencha.gxt.widget.core.client.menu.MenuItem;
import com.sencha.gxt.widget.core.client.toolbar.PagingToolBar;
import com.vision.core.cl.BaseModule;
import com.vision.core.cl.Callback;
import com.vision.core.cl.event.CreatedEvent;
import com.vision.core.cl.event.CreatedEvent.CreationHandler;
import com.vision.core.cl.ui.ConfirmDialogHandler;
import com.vision.core.cl.ui.Notifications;
import com.vision.core.cl.ui.UI;
import com.vision.core.cl.ui.component.BasicGridView;
import com.vision.core.cl.ui.component.BasicPagingLoader;
import com.vision.core.cl.ui.component.CompanyComboBox;
import com.vision.core.cl.ui.component.EnumComboBox;
import com.vision.core.cl.ui.component.MultiSelectListAndDetailPanel;
import com.vision.core.cm.db.data.Company;
import com.vision.sales.cl.SalesServices;
import com.vision.sales.cl.SalesTasks;
import com.vision.sales.cl.data.DeliveryReceiptProperties;
import com.vision.sales.cl.data.SalesInvoiceProperties;
import com.vision.sales.cl.event.SalesInvoiceCreatedEvent;
import com.vision.sales.cl.event.SalesInvoiceDeletedEvent;
import com.vision.sales.cl.resource.SalesResources;
import com.vision.sales.cl.ui.component.CustomerComboBox;
import com.vision.sales.cl.ui.component.ProductComboBox;
import com.vision.sales.cl.ui.component.SalesmanComboBox;
import com.vision.sales.cl.ui.component.TransactionLoadConfig;
import com.vision.sales.cl.ui.component.TransactionNoCell;
import com.vision.sales.cl.ui.component.TransactionStatusCell;
import com.vision.sales.cm.data.CollectionStatus;
import com.vision.sales.cm.data.TransactionStatus;
import com.vision.sales.cm.db.data.CollectionItem;
import com.vision.sales.cm.db.data.Customer;
import com.vision.sales.cm.db.data.DeliveryReceipt;
import com.vision.sales.cm.db.data.Product;
import com.vision.sales.cm.db.data.SalesInvoice;
import com.vision.sales.cm.db.data.SalesInvoice.FieldSpecs;
import com.vision.sales.cm.db.data.Salesman;
import com.vision.sales.collection.cl.ui.BasicCollectionItemGridPanel;

/**
 * 
 * @author Mark
 *
 */
public class SalesInvoicesPanel extends MultiSelectListAndDetailPanel<SalesInvoice> implements Editor<SalesInvoice> {

	interface Binder extends UiBinder<Widget, SalesInvoicesPanel> { }

	private static final Binder binder = GWT.create(Binder.class);
	
	@UiField VerticalLayoutContainer mainPanel;
	
	// Ignored by the form driver since these are not fields in the SalesInvoice
	@Ignore @UiField StoreFilterField<SalesInvoice> gridFilter;
	@Ignore @UiField TextButton filterBtn;
	@Ignore @UiField MenuItem statusMenuItem;
		@Ignore @UiField CheckMenuItem pendingOnlyMenuItem;
		@Ignore @UiField CheckMenuItem postedOnlyMenuItem;
		@Ignore @UiField CheckMenuItem allStatusMenuItem;
	
	@Ignore @UiField TextButton addBtn;
	@Ignore @UiField TextButton postBtn;
	@Ignore @UiField TextButton moreBtn;
	@Ignore @UiField MenuItem refreshMenuItem;
	@Ignore @UiField MenuItem deleteMenuItem;
	
	@UiField Grid<SalesInvoice> grid;
	@UiField PagingToolBar pagingToolbar;
	PagingLoader<PagingLoadConfig, PagingLoadResult<SalesInvoice>> loader;
	
	// Form fields that are bound by the form driver to the fields in the SalesInvoice class.
	// The name of these form fields must match the name of the field in the SalesInvoice class.
	@UiField CompanyComboBox company;
	@UiField DateField date;
	@UiField TextField invoiceNo;
	@UiField TextField poNo;
	
	@UiField(provided = true) NumberPropertyEditor<Double> doublePropertyEditor = new DoublePropertyEditor();
	@UiField(provided = true) NumberFormat numberFormat = NumberFormat.getFormat("#,##0.00");
	@UiField NumberField<Double> grossSales;
	
	@UiField CustomerComboBox customer;
	@UiField ProductComboBox product;
	@UiField SalesmanComboBox salesman;
	
	@UiField TextArea itemsDelivered;
	@UiField TextArea remarks;
	
	@UiField SimpleComboBox<CollectionStatus> collectionStatus;
	
	// Summary Fields
	@Ignore @UiField NumberField<Double> payments;
	@Ignore @UiField NumberField<Double> overruns;
	@Ignore @UiField NumberField<Double> overpayments;
	@Ignore @UiField NumberField<Double> discounts;
	@Ignore @UiField NumberField<Double> rejects;
	@Ignore @UiField NumberField<Double> returns;
	@Ignore @UiField NumberField<Double> taxes;
	@Ignore @UiField NumberField<Double> balance;
	
	// Ignored by the form driver since these are not fields in the SalesInvoice
	@Ignore @UiField TextButton saveBtn;
	@Ignore @UiField TextButton cancelBtn;
	
	// Interface used to bind the form fields to the SalesInvoice fields
	interface SalesInvoiceDriver extends SimpleBeanEditorDriver<SalesInvoice, SalesInvoicesPanel> { }
	
	// Instance of the SalesInvoiceDriver interface
	private SalesInvoiceDriver driver = GWT.create(SalesInvoiceDriver.class);
	
	@UiField(provided = true) Grid<DeliveryReceipt> deliveryReceiptsGrid;
	@UiField BasicCollectionItemGridPanel collectionItemsGrid;
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	public SalesInvoicesPanel() {
		// Global Handlers -- should be registered only once
		BaseModule.addHandler(SalesInvoiceCreatedEvent.TYPE, new CreationHandler<SalesInvoice>() {
			@Override
			public void onCreated(CreatedEvent<SalesInvoice> e) {
				grid.getStore().add(e.getObject());
			}
		});
		
		deliveryReceiptsGrid = initializeDeliveryReceiptsGrid();
		collectionItemsGrid = initializeCollectionItemsGrid();
		
		setWidget(binder.createAndBindUi(this));
		
		// Bind the filter into the grid's store
		gridFilter.bind(grid.getStore());
		
		// Initialize the driver, used to run the form editor
		driver.initialize(this);
		
		date.setPropertyEditor(UI.datePropertyEditor());
		invoiceNo.addValidator(new MaxLengthValidator(FieldSpecs.INVOICE_NO_MAX));
		poNo.addValidator(new MaxLengthValidator(FieldSpecs.PO_NO_MAX));
		itemsDelivered.addValidator(new MaxLengthValidator(FieldSpecs.ITEMS_DELIVERED_MAX));
		remarks.addValidator(new MaxLengthValidator(FieldSpecs.REMARKS_MAX));
		
		grossSales.addStyleName("numfield-ralign");
		
		// Initialize loaders
		RpcProxy<PagingLoadConfig, PagingLoadResult<SalesInvoice>> proxy = new RpcProxy<PagingLoadConfig, PagingLoadResult<SalesInvoice>>() {
		    @Override
		    public void load(PagingLoadConfig loadConfig, AsyncCallback<PagingLoadResult<SalesInvoice>> callback) {
		    	TransactionLoadConfig tConfig = new TransactionLoadConfig(loadConfig);
		    	setFilterInfo(tConfig);
		    	SalesServices.salesInvoiceSvc().getList(tConfig, callback);
		    }
	    };
	    
	    loader = new BasicPagingLoader<SalesInvoice>(proxy, grid.getStore());
	    loader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, SalesInvoice, PagingLoadResult<SalesInvoice>>(grid.getStore()) {
        	@Override
        	public void onLoad(LoadEvent<PagingLoadConfig, PagingLoadResult<SalesInvoice>> event) {
        		super.onLoad(event);
        		grid.getSelectionModel().deselectAll();
        		edit(null);
        	}
        });
        
        grid.setLoader(loader);
        grid.setLoadMask(true);
		
		pagingToolbar.bind(loader);
	}
	
	@Override
	protected SimpleBeanEditorDriver<SalesInvoice, ? extends MultiSelectListAndDetailPanel<SalesInvoice>> getDriver() {
		return driver;
	}
	
	// UiFactory Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@Ignore
	@UiFactory
	StoreFilterField<SalesInvoice> initializeGridFilter() {
		StoreFilterField<SalesInvoice> f = new StoreFilterField<SalesInvoice>() {
			@Override
			protected boolean doSelect(Store<SalesInvoice> store, SalesInvoice parent, SalesInvoice item, String filter) {
				String filterInLowerCase = filter.toLowerCase().trim();
				return item.getGroupAndNo().toLowerCase().contains(filterInLowerCase);
			}
		};
		return f;
	}

	/**
	 * Used to create the 'grid' field in the XML file. 
	 * 
	 * @return
	 */
	@UiFactory
	Grid<SalesInvoice> initializeGrid() {
		SalesInvoiceProperties props = SalesInvoiceProperties.INSTANCE; 
		List<ColumnConfig<SalesInvoice, ?>> columns = new ArrayList<ColumnConfig<SalesInvoice, ?>>();
		
		ListStore<SalesInvoice> store = new ListStore<SalesInvoice>(props.key());

		columns.add(UI.column(props.date(), 40, "Date", UI.dateCell()));
		ColumnConfig<SalesInvoice, String> companyCol = UI.column(props.companyCode(), 40, "Company");
		companyCol.setHidden(true);
		columns.add(companyCol);
		columns.add(UI.column(props.groupAndNo(), 45, "Invoice No.", new TransactionNoCell<SalesInvoice>(store)));
		columns.add(UI.column(props.customerCode(), 70, "Customer"));
		columns.add(UI.column(props.productCode(), 70, "Product"));
		columns.add(UI.column(props.poNo(), 50, "PO No."));
		columns.add(UI.column(props.grossSales(), 45, "Gross Sales", UI.decimalCell(), HasHorizontalAlignment.ALIGN_RIGHT));
		columns.add(UI.column(props.balance(), 45, "Balance", UI.decimalCell(), HasHorizontalAlignment.ALIGN_RIGHT));
		ColumnConfig<SalesInvoice, TransactionStatus> statusCol = UI.column(props.status(), 30, "Status", TransactionStatusCell.INSTANCE, HasHorizontalAlignment.ALIGN_CENTER);
		statusCol.setHidden(true);
		columns.add(statusCol);
		
		ColumnModel<SalesInvoice> cm = new ColumnModel<SalesInvoice>(columns);

		Grid<SalesInvoice> grid = new Grid<SalesInvoice>(store, cm);
		grid.setAllowTextSelection(false);
		grid.getSelectionModel().setSelectionMode(SelectionMode.MULTI);
		
		GridView<SalesInvoice> view = new BasicGridView<SalesInvoice>();
		view.setAutoExpandColumn(columns.get(3));
		view.setEmptyText("There are no sales invoices to display. Create an invoice from a delivery receipt first.");
		grid.setView(view);
		
		initGridHandlers(grid);
		
		return grid;
	}
	
	Grid<DeliveryReceipt> initializeDeliveryReceiptsGrid()
	{		
		DeliveryReceiptProperties prop = DeliveryReceiptProperties.INSTANCE;
		
		List<ColumnConfig<DeliveryReceipt, ?>> columns = new ArrayList<ColumnConfig<DeliveryReceipt, ?>>();
		
		columns.add(UI.column(prop.date(), 45, "Date", UI.dateCell()));
		columns.add(UI.column(prop.drNo(), 60, "D/R No."));
		columns.add(UI.column(prop.customerCode(), 60, "Customer"));
		
		AbstractCell<SalesInvoice> invoiceNoCell = new AbstractCell<SalesInvoice>() {
			@Override
			public void render(Context context, SalesInvoice value, SafeHtmlBuilder sb) {
				sb.append(SafeHtmlUtils.fromString(value == null ? "" : value.getGroupAndNo()));
			}
		};
		columns.add(UI.column(prop.salesInvoice(), 60, "Invoice No.", invoiceNoCell));
		columns.add(UI.column(prop.remarks(), 150, "Remarks"));
		
		GridView<DeliveryReceipt> view = new BasicGridView<DeliveryReceipt>();
		view.setAutoExpandColumn(columns.get(columns.size() - 1));
		view.setEmptyText("There are no delivery receipts to display.");
		
		Grid<DeliveryReceipt> grid = new Grid<DeliveryReceipt>(
				new ListStore<DeliveryReceipt>(DeliveryReceiptProperties.INSTANCE.key()), 
				new ColumnModel<DeliveryReceipt>(columns), 
				view);
		
		return grid;
	}

	BasicCollectionItemGridPanel initializeCollectionItemsGrid() {
		BasicCollectionItemGridPanel grid = new BasicCollectionItemGridPanel();
		return grid;
	}
	
	@Ignore
	@UiFactory
	SimpleComboBox<CollectionStatus> initializeCollectionStatusCombo() {
		return new EnumComboBox<CollectionStatus>(CollectionStatus.values());
	}
	
	// Logic %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@Override
	protected void edit(SalesInvoice invoice) {
		super.edit(invoice);
		
		boolean hasInvoice = invoice != null;
		
		saveBtn.setEnabled(hasInvoice);
		cancelBtn.setEnabled(hasInvoice);
		
		loadInvoiceSummary(invoice);
		
		loadDeliveryReceiptsOfInvoice(invoice);
		loadCollectionItemsOfInvoice(invoice);
	}
	
	private void loadInvoiceSummary(final SalesInvoice invoice) {
		if (invoice == null)
			return;
		
		SalesServices.salesInvoiceSvc().getSalesInvoiceSummary(invoice.getId(), new Callback<CollectionItem>() {
			@Override
			protected void handleSuccess(CollectionItem result) {
				payments.setValue(result.getAmount());
				overruns.setValue(result.getOverruns());
				overpayments.setValue(result.getOverpayments());
				discounts.setValue(result.getDiscounts());
				rejects.setValue(result.getRejects());
				returns.setValue(result.getReturns());
				taxes.setValue(result.getTax());
				balance.setValue(invoice.getBalance());
			}
		});
	}
	
	private void loadDeliveryReceiptsOfInvoice(SalesInvoice invoice) {
		deliveryReceiptsGrid.getStore().clear();
		
		if (invoice == null)
			return;
		
		UI.mask(deliveryReceiptsGrid, "Loading Delivery Receipts...");
		SalesServices.salesInvoiceSvc().getDeliveryReceiptsByInvoice(invoice.getId(), new Callback<List<DeliveryReceipt>>(deliveryReceiptsGrid) {
			@Override
			protected void handleSuccess(List<DeliveryReceipt> deliveryReceipts) {
				deliveryReceiptsGrid.getStore().addAll(deliveryReceipts);
			}
		});
	}
	
	private void loadCollectionItemsOfInvoice(SalesInvoice invoice) {
		collectionItemsGrid.getStore().clear();
		
		if (invoice == null)
			return;
		
		UI.mask(collectionItemsGrid, "Loading Collection Items...");
		SalesServices.salesInvoiceSvc().getCollectionItemsByInvoice(invoice.getId(), new Callback<List<CollectionItem>>(collectionItemsGrid) {
			@Override
			protected void handleSuccess(List<CollectionItem> collectionItems) {
				collectionItemsGrid.getStore().addAll(collectionItems);
			}
		});
	}

	// Listeners %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@UiHandler("statusMenu")
	void onStatusSelection(SelectionEvent<Item> e) {
		loadData();
	}
	
	@UiHandler("addBtn")
	void addClicked(SelectEvent e) {
		CreateSalesInvoiceWindow csiw = new CreateSalesInvoiceWindow();
		Window w = (Window) csiw.asWidget();
		w.show();
	}
	
	// Called when the 'Post' button is clicked
	@UiHandler("postBtn")
	void postClicked(SelectEvent e) {
		List<SalesInvoice> selected = grid.getSelectionModel().getSelectedItems();
		if (selected.isEmpty()) {
			Notifications.info("Please select at least one sales invoice.");
			return;
		}
		
		mainPanel.mask("Posting sales invoices...");
		SalesServices.salesInvoiceSvc().postSalesInvoices(selected, new Callback<List<SalesInvoice>>(mainPanel) {
			@Override
			protected void handleSuccess(List<SalesInvoice> result) {
				for (SalesInvoice invoice : result)
					grid.getStore().update(invoice);
			}
		});
	}
	
	@UiHandler("moreBtnMenu")
	void onMenuSelection(SelectionEvent<Item> e) {
		Item item = e.getSelectedItem();
		if (item == refreshMenuItem) {
			refreshClicked();
		} else if (item == deleteMenuItem) {
			deleteClicked();
		}
	}
	
	// Called when the 'Refresh' button is clicked
	void refreshClicked() {
		loadData();
	}
	
	// Called when the 'Delete' button is clicked
	void deleteClicked() {
		final SalesInvoice selected = grid.getSelectionModel().getSelectedItem();
		if (selected == null)
			return;
		
		if (selected.getStatus() != TransactionStatus.PENDING) {
			Notifications.info("You cannot delete a sales invoice that has already been posted.");
			return;
		}
		
		if (selected.getCollectionStatus() != CollectionStatus.UNPAID) {
			Notifications.info("You cannot delete a sales invoices that has already been paid.");
			return;
		}
		
		UI.confirm("Confirm Delete", "Are you sure you want to delete '" + selected.getInvoiceNo() + "'?",
			new ConfirmDialogHandler() {
				@Override
				public void onYes(HideEvent event) {
					UI.mask(mainPanel, "Deleting " + selected.getGroupAndNo() + "...");
					salesInvoiceSvc().delete(selected, new Callback<SalesInvoice>(mainPanel) {
						@Override
						protected void handleSuccess(SalesInvoice result) {
							grid.getStore().remove(result);
							BaseModule.fireEvent(new SalesInvoiceDeletedEvent(result));
							
							// Clear the form editor if necessary
							SalesInvoice inEditor = driver.flush();
							if (inEditor != null && inEditor.getId().equals(result.getId()))
								edit(null);
						}
					});
				}
			}
		);
	}
	
	// Called when the 'Save' button is clicked
	@UiHandler("saveBtn")
	void saveClicked(SelectEvent e) {
		SalesInvoice salesInvoice = driver.flush();
		if (driver.hasErrors())
			return;
		
		UI.mask(mainPanel, "Updating sales invoice...");
		salesInvoiceSvc().update(salesInvoice, new Callback<SalesInvoice>(mainPanel) {
			@Override
			protected void handleSuccess(SalesInvoice result) {
				grid.getStore().update(result);
				edit(result);
			}
		});
	}
	
	// Called when the 'Cancel' button is clicked
	@UiHandler("cancelBtn")
	void cancelClicked(SelectEvent e) {
		edit(null);
	}
	 
	// ITabItemPanel Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@Override
	public String getPanelId() {
		return SalesTasks.SALES_INVOICES.getId();
	}
	
	@Override
	public TabItemConfig getConfig() {
		if (config == null) {
			config = new TabItemConfig("Sales Invoices", true);
			config.setIcon(SalesResources.INSTANCE.salesInvoices());
		}
		return config;
	}
	
	@Override
	public void loadData() {
		Log.debug("Loading salesmen, companies, customers, products for dropdown...");

		// TODO 0 Consider using company.loadCompany();
		UI.mask(company, "Loading company...");
		companySvc().getNameAndIdOnly(new Callback<List<Company>>(company) {
			@Override
			protected void handleSuccess(List<Company> result) {
				company.getStore().clear();
				company.getStore().addAll(result);
			}
		});
		
		// TODO 0 Consider using salesman.loadSalemen();
		UI.mask(salesman, "Loading salesmen...");
		salesmanSvc().getSalesmenNameAndIdOnly(new Callback<List<Salesman>>(salesman) {
			@Override
			protected void handleSuccess(List<Salesman> result) {
				salesman.getStore().clear();
				salesman.getStore().addAll(result);
			}
		});
		
		// TODO 0 Consider using customer.loadCustomers();
		UI.mask(customer, "Loading customers...");
		customerSvc().getCustomerNameAndIdOnly(new Callback<List<Customer>>(customer) {
			@Override
			protected void handleSuccess(List<Customer> result) {
				customer.getStore().clear();
				customer.getStore().addAll(result);
			}
		});
		
		// TODO 0 Consider using product.loadProducts();
		UI.mask(product, "Loading products...");
		productSvc().getProductNameAndIdOnly(new Callback<List<Product>>(product) {
			@Override
			protected void handleSuccess(List<Product> result) {
				product.getStore().clear();
				product.getStore().addAll(result);
			}
		});
		
		// Load data
		Log.debug("Loading Sales Invoices...");
		loader.load();
		edit(null);
	}
	
	// Helper Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	void setFilterInfo(TransactionLoadConfig config) {
		// Status
		if (pendingOnlyMenuItem.isChecked())
			config.setStatuses(TransactionStatus.PENDING);
		else if (postedOnlyMenuItem.isChecked())
			config.setStatuses(TransactionStatus.POSTED);
		else
			config.setStatuses((List<TransactionStatus>) null);
	}
	
}
